﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace VolunteerHubAdapter.MVVM.ViewModels
{

    /// <summary>
    /// provides some simplified NotifyPropertyChangedLogic
    /// </summary>
    public abstract class ViewModelBase : System.ComponentModel.INotifyPropertyChanged
    {
        #region " Property Changed Functionality "
        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
        public delegate void PropertyChangedEventHandler(object sender, System.ComponentModel.PropertyChangedEventArgs e);

        //protected void OnPropertyChanged()
        //{
        //    string caller = null;
        //    System.Diagnostics.StackTrace x = new System.Diagnostics.StackTrace();
        //    //get the method name that called our OnPropertyChanged method
        //    caller = x.GetFrame(1).GetMethod().Name;
        //    //since it will be a property, it will be prefixed with set_ which we need to strip off
        //    caller = caller.Substring(startIndex: 4);//.Replace("set_", "");
        //    if (PropertyChanged != null)
        //    {
        //        PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName: caller));
        //    }
        //}

        protected virtual void OnPropertyChanged(System.Linq.Expressions.Expression<Func<object>> expression)
        {
            //TODO: add unary check
            if ((expression.NodeType != System.Linq.Expressions.ExpressionType.Lambda))
                throw new ArgumentException("Value must be a lamda expression", "expression");

            dynamic body = (System.Linq.Expressions.MemberExpression)expression.Body;

            if (PropertyChanged != null)
            {
                PropertyChanged(sender: this, e: new System.ComponentModel.PropertyChangedEventArgs(propertyName: body.Member.Name));
            }
        }

        protected void OnPropertyChanged(String propertyName = null)
        {
            if (PropertyChanged != null)
            {
                if (propertyName == null)
                {
                    System.Diagnostics.StackTrace x = new System.Diagnostics.StackTrace();
                    //get the method name that called our OnPropertyChanged method
                    propertyName = x.GetFrame(1).GetMethod().Name;
                    //since it will be a property, it will be prefixed with set_ which we need to strip off
                    System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("set_", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                    propertyName = r.Replace(input: propertyName, replacement: "", count: 1);
                }

                PropertyChanged(sender: this, e: new System.ComponentModel.PropertyChangedEventArgs(propertyName: propertyName));
            }
        }
        #endregion
    }

}
